<script>
import { websocketObj } from "@/utils/websocket.js";
import { getUserInfo } from "@/common/auth.js";
import {
  chatMsgBuilder,
  chatMsgHandler,
  chatSnapshotBuilder,
  networkStatus,
  setChatMsg,
  setChatSnapshot,
} from "./utils/chat_utils";
import { ChatSnapshot, DataContent, PrivateChatMsg } from "./utils/chatObject";
import { getNettyUrl } from "./utils/constants";
import { getToken } from './common/auth';
export default {
  onLaunch: function () {
    let that = this;
    uni.$on("setVuexUserInfo", function (data) {
      that.setVuexUserInfo(data.user, data.isLoginPage);
    });
    uni.$on("init", this.init);
    uni.$on("unsignedHandler", this.unsignedHandler);
    networkStatus();
    websocketObj.socket(
      getNettyUrl(),
      this.getWebsocketData,
      this.getWebsocketError
    );
    if(!isEmpty(getToken())){
      this.$fim.msgCallback = this.msgCallback;
    }
  },
  onShow: function () {},
  onHide: function () {},
  methods: {
    // 断线重连或用户刷新浏览器之后的初始化
    init() {
      let userId = null;
      if (this.$u.test.isEmpty(this.$store.getters.id)) {
        // 如果本地存在用户信息则把当前用户和socket绑定在一起，不存在则登录之后再绑定
        let user = getUserInfo();
        if (user != null && !this.$u.test.isEmpty(user.id)) {
          userId = user.id;
        }
      } else {
        userId = this.$store.getters.id;
      }
      if (!this.$u.test.isEmpty(userId)) {
        websocketObj.sendMsg(
          new DataContent(
            1,
            new PrivateChatMsg(userId, null, null, null, null),
            null
          )
        );
        // 获取断线重连未接收的消息
        this.unsignedHandler(userId);
      }
    },
    // 获取未签收消息
    async queryUnsignedChatMsg(id) {
      return await this.$u.api.queryUnsignedMsg(id);
    },
    /**
     * 未签收消息处理器，ID相同的只保留最后一条消息，数量等于同一个用户消息的数量
     */
    unsignedHandler(id) {
      this.queryUnsignedChatMsg(id).then((res) => {
        let map = new Map();
        let unsignedList = res.data;
        if (unsignedList != null && unsignedList.length !== 0) {
          // 签收消息
          this.signMsg(this.$u.deepClone(unsignedList), id);
          for (let unsigned of unsignedList) {
            unsigned.content = JSON.parse(unsigned.content);
            let chatSnapshotMsg = map.get(unsigned.uid);
            if (chatSnapshotMsg != null) {
              chatSnapshotMsg.count = chatSnapshotMsg.count + 1;
              chatSnapshotMsg.msg = chatSnapshotBuilder(unsigned);
            } else {
              map.set(
                unsigned.uid,
                new ChatSnapshot(
                  unsigned.uid,
                  chatSnapshotBuilder(unsigned),
                  1,
                  unsigned.gmtCreate,
                  unsigned.type,
                  false
                )
              );
            }
          }
        }
        // 存储聊天快照消息
        map.forEach((v, k) => {
          setChatSnapshot(id, v);
        });
        // 执行一次之后就不需要监听，防止首页的emit一直执行
        uni.$off("unsignedHandler");
      });
    },
    // 签收消息
    signMsg(data, id) {
      if (data != null && data.length !== 0) {
        let ids = "";
        for (let msg of data) {
          if (msg.type === 3) {
            msg.length = msg.extend;
          } else if (msg.type === 4) {
            let w = msg.extend.split(":")[0];
            let h = msg.extend.split(":")[1];
            msg.w = w;
            msg.h = h;
          } else {
            msg.content = JSON.parse(msg.content);
          }
          setChatMsg(id, msg.uid, msg);
          ids += msg.id + ",";
        }
        let dataContent = new DataContent(4, null, ids);
        websocketObj.sendMsg(dataContent);
      }
    },
    // websocket函数回调：返回监听的数据
    msgCallback(msgKey, msg){

    },
    // websocket函数回调：返回监听的数据
    getWebsocketData(val) {
      let msgObj = JSON.parse(val);
      let msg = msgObj.msg;
      if (this.$u.test.isEmpty(this.$store.getters.id)) {
        this.setVuexUserInfo(null, false);
      }
      if (msgObj.type === 1) {
        chatMsgHandler(this.$store.getters.id, msg);
        uni.$emit("receivePrivateMsg", msg);
      } else if (msgObj.type === 2) {
        uni.$emit("receiveNotifyMsg", msg);
      } else if (msgObj.type === 3) {
        console.log(msg);
      } else {
        chatMsgBuilder(msg);
        uni.$emit("receiveGroupMsg", {
          msg: msg,
          groupId: msgObj.extend,
        });
      }
    },
    //websocket函数抛错： 返回错误信息 用于用户提示
    getWebsocketError(err) {
      console.log(err);
    },
    setVuexUserInfo(user, isLoginPage) {
      let isEmptyStr = this.$u.test.isEmpty(this.$store.getters.id);
      if (!isLoginPage && isEmptyStr) {
        user = getUserInfo();
        // 如果缓存为空则跳转到登录页面
        if (user == null && !isLoginPage) {
          let pages = getCurrentPages();
          if (pages.pop().route !== "pages/login/login") {
            this.$u.route({
              type: "reLaunch",
              url: "/pages/login/login",
            });
          }
        }
      }
      if (isLoginPage || isEmptyStr) {
        if (user != null) {
          this.$store.commit("SET_ROLE", user.role);
          this.$store.commit("SET_ID", user.id);
          this.$store.commit("SET_NAME", user.name);
          this.$store.commit("SET_NUM", user.num);
          this.$store.commit("SET_EMAIL", user.email);
          this.$store.commit("SET_AVATAR", user.avatar);
          this.$store.commit("SET_CLAZZ_ID", user.clazzId);
        }
      }
    },
  },
  beforeDestroy() {
    websocketObj.stop();
  },
};
</script>

<style lang="scss">
/*每个页面公共css */
@import "static/css/iconfont.css";
@import "uview-ui/index.scss";
</style>
